package com.ruoyi.wechat.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.wechat.domain.CodeSession;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * <p>
 * 微信助手
 * </p>
 *
 * @author YinHeng
 * @since 2024/2/18
 */
@Component
public class WechatHelper {

    /**
     * 你自己的微信小程序appId
     */
    @Value("${wechat.appId}")
    private static String APP_ID;

    /**
     * 你自己的微信APP密钥
     */
    @Value("${wechat.appSecret}")
    private static String APP_SECRET;

    @Autowired
    public void init(@Value("${wechat.appId}") String appId,
                     @Value("${wechat.appSecret}") String appSecret) {
        WechatHelper.APP_ID = appId;
        WechatHelper.APP_SECRET = appSecret;
    }

    public static CodeSession getCodeSession(String code) {
        //微信官方提供的微信小程序登录授权时使用的URL地址
        String url = "https://api.weixin.qq.com/sns/jscode2session";
        url += "?appid=" + APP_ID + "&secret=" + APP_SECRET + "&js_code=" + code + "&grant_type=authorization_code";
        //开始发起网络请求,若依管理系统自带网络请求工具，直接使用即可
        String res = HttpUtils.sendGet(url);
        JSONObject result = JSON.parseObject(res);
        CodeSession codeSession = new CodeSession();
        codeSession.setSessionKey(result.getString("session_key"));
        codeSession.setOpenid(result.getString("openid"));
        return codeSession;
    }


    /**
     * 解密
     *
     * @param sessionKey
     * @param encryptedData
     * @param iv
     * @return
     */
    public static String decrypt(String sessionKey, String encryptedData, String iv) {
        try {
            byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
            byte[] encryptedDataBytes = Base64.decodeBase64(encryptedData);
            byte[] ivBytes = Base64.decodeBase64(iv);

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            SecretKeySpec sKeySpec = new SecretKeySpec(sessionKeyBytes, "AES");
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes);
            cipher.init(Cipher.DECRYPT_MODE, sKeySpec, ivParameterSpec);

            byte[] decrypted = cipher.doFinal(encryptedDataBytes);
            return new String(decrypted, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
